//
//  EVEAPIServerStatus.m
//  EVE Mac Suite
//
//  Created by Vadim Lozko on 2/7/09.
//  Copyright 2009 __Vadim__. All rights reserved.
//

#import "EVEAPIServerStatus.h"
#import "EVEAPICoreDataController.h"
#import "EVECDServer.h"

@implementation EVEAPIServerStatus

+(EVEAPIServerStatus*)serverStatus
{
	static EVEAPIServerStatus *serverStatus;
	
	@synchronized(self)
	{
		if (!serverStatus)
		{
			serverStatus = [[EVEAPIServerStatus alloc] init];
		}
		return serverStatus;
	}
	return nil;
}

#pragma mark EVEAPIDataHandler protocol methods



-(NSString*)xmlStorePath
{
	return [[EMSGeneralUtils applicationSupportFolder] stringByAppendingPathComponent: @"ServerStatus.xml"];
}

-(NSString*)APIDocumentType
{
	return SERVER_STATUS_API_TYPE;
}

-(void)updateCoreDataStore
{	
	//[EVECDContext lock];
	//[[EVEAPICoreDataController coreDataController] performSelectorOnMainThread:@selector(lockContext) withObject:nil waitUntilDone:YES];
	NSError* error = nil;
	EVECDServer* server = (EVECDServer*)[EVECDContext fetchObjectForEntityName:@"EVECDServer" withPredicate:nil];
	if(!server)
	{
		server = [NSEntityDescription insertNewObjectForEntityForName:@"EVECDServer" 
											   inManagedObjectContext:EVECDContext];
	}
	
	//Server Status
	NSArray* serverStatusArray = [xmlDoc nodesForXPath:@"//serverOpen" error:&error];
	if([serverStatusArray count] == 1)
	{
		NSString* serverStatusString = [[serverStatusArray objectAtIndex:0] stringValue];
		if([serverStatusString isEqualToString:@"True"])
		{
			server.serverStatus = (NSNumber*)kCFBooleanTrue;
		} else {
			server.serverStatus = (NSNumber*)kCFBooleanFalse;
		}
	}
	
	//Server Players online
	NSArray* playersOnlineArray = [xmlDoc nodesForXPath:@"//onlinePlayers" error:&error];
	if([playersOnlineArray count] == 1)
	{
		double playersOnline = [[[playersOnlineArray objectAtIndex:0] stringValue] doubleValue];
		server.playersOnline = [NSNumber numberWithDouble:playersOnline];
	}
	[[EVEAPICoreDataController coreDataController] saveData];
	//[EVECDContext unlock];
	//[[EVEAPICoreDataController coreDataController] performSelectorOnMainThread:@selector(unlockContext) withObject:nil waitUntilDone:YES];
	[self updateDidFinish:(NSNumber*)kCFBooleanTrue];
}

-(void)verifyCoreDataStore
{
	[self updateCoreDataStore];
}

-(void)downloadRequestDidFinishForXMLDoc:(NSXMLDocument*)document 
{
	NSError* error = nil;
	if([self xmlDocValid:document])
	{
		NSData* xmlData = [document XMLData];
		if([[NSFileManager defaultManager] fileExistsAtPath:[self xmlStorePath]])
		{
			[[NSFileManager defaultManager] removeFileAtPath:[self xmlStorePath] handler:nil];
		}
		[xmlData writeToFile:[self xmlStorePath] options:NSXMLDocumentTidyXML error:&error];
		if(xmlDoc)
		{
			[xmlDoc release];
		}
		xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[self xmlStorePath]]
													  options:NSXMLDocumentTidyXML
														error:&error];
		[self updateCoreDataStore];
		[self startUpdateTimer];
	} else {
		if([[NSFileManager defaultManager] fileExistsAtPath:[self xmlStorePath]])
		{
			xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL fileURLWithPath:[self xmlStorePath]]
														  options:NSXMLDocumentTidyXML
															error:&error];
			[self verifyCoreDataStore];
		}
		[self documentDidDownload:NO];
	}
	if(error)
	{
		[self documentDidDownload:NO];
		NSLog(@"Error writing xml file: %@", [error localizedDescription]);
	}
	[self documentDidDownload:YES];
}

-(void)downloadRequestDidFailWithError:(NSError*)error
{
	NSString* offlineServerXMLPath = [[NSBundle mainBundle] pathForResource:@"BlankServerStatus" ofType:@"xml"];
	if(xmlDoc)
	{
		[xmlDoc release];
	}
	xmlDoc = [[NSXMLDocument alloc] initWithContentsOfURL:[NSURL fileURLWithPath:offlineServerXMLPath] 
												  options:NSXMLDocumentTidyXML
													error:nil];
	NSXMLNode* root = [xmlDoc childAtIndex:0];
	NSString* nowServerTimeString = [[NSDate date] descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" 
																		timeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"] 
																		  locale:nil];
	[[root childAtIndex:0] setObjectValue:nowServerTimeString];
	NSString* threeMinutesFromNowString = [[NSDate dateWithTimeIntervalSinceNow:180.0] 
										   descriptionWithCalendarFormat:@"%Y-%m-%d %H:%M:%S" 
										   timeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]  
										   locale:nil];
	[[root childAtIndex:2] setObjectValue:threeMinutesFromNowString];
	[self updateCoreDataStore];
	[self cachedDataCurrent];
	[self startUpdateTimer];
}

-(void)documentDidDownload:(BOOL)success;
{
	if([delegate respondsToSelector:@selector(serverStatusXMLDownloadDidFinish:)])
	{
		[delegate serverStatusXMLDownloadDidFinish:success];
	}
}

@end
